package com.amigo.online.provider.user.config;


import com.amigo.online.common.base.exception.BaseException;
import com.amigo.online.common.core.response.Meta;
import com.amigo.online.common.core.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@ControllerAdvice
@RestController
@RequestMapping( value = "/error")
@Slf4j
public class ControllerException {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result httpRequestMethodNotSupportedException(HttpServletResponse response , Exception e) {
        log.debug("450",e);
        response.setStatus(200);
        return Result.error(405, "method 方法不支持");
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public Result httpMediaTypeNotSupportedException(HttpServletResponse response) {
        response.setStatus(200);
        return Result.error(415, "不支持媒体类型");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result notFoundPage404(HttpServletResponse response) {
        response.setStatus(200);
        return Result.error(404,"没有找到访问资源");
    }

    @RequestMapping(value = "/401" ,produces = {"application/json;charset=UTF-8"})
    public Result forbidden401(HttpServletResponse response) {
        response.setStatus(200);
        System.out.println("401");
        return Result.error(401,"没有访问权限");
    }

    @RequestMapping(value = "/403" ,produces = {"application/json;charset=UTF-8"})
    public Result forbidden403(HttpServletResponse response) {
        response.setStatus(200);
        System.out.println("403");
        return Result.error(403,"没有访问权限");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result defaultException(HttpServletResponse response,Exception e) {
        response.setStatus(200);
        log.error("系统内部错误", e);
        return Result.error(500, "系统内部错误");
    }

    /**
     * 业务异常.
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result businessException(BaseException ex) {
        Meta meta = new Meta();
        ex.handler(meta);
        log.error("业务异常 => {}", meta.getMsg());
        return Result.error(meta.getMsg());
    }
}